package com.core.cloudgateway.config;

import org.springframework.cloud.gateway.event.RefreshRoutesEvent;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionLocator;
import org.springframework.cloud.gateway.route.RouteDefinitionWriter;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;

/**
 * @author =====Lqj=====
 * @className DynamicRouteService
 * @description 动态路由转发
 * @create 2024/11/13 18:54
 **/
@Service
@SuppressWarnings("all")
public class DynamicRouteService implements ApplicationEventPublisherAware {

    //写路由定义
    private final RouteDefinitionWriter routeDefinitionWriter;
    //获取路由定义
    private final RouteDefinitionLocator routeDefinitionLocator;
    //事件发布
    private ApplicationEventPublisher publisher;

    public DynamicRouteService(RouteDefinitionWriter routeDefinitionWriter,
                               RouteDefinitionLocator routeDefinitionLocator) {
        this.routeDefinitionWriter = routeDefinitionWriter;
        this.routeDefinitionLocator = routeDefinitionLocator;
    }

    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        // 完成事件推送句柄的初始化
        this.publisher = applicationEventPublisher;
    }

    /**
     * 增加路由定义
     */
    public boolean addRouteDefinition(RouteDefinition definition) {
        //log.info("添加路由规则: {}", definition);
        // 保存路由配置并发布
        routeDefinitionWriter.save(Mono.just(definition)).subscribe();
        // 发布事件通知给 Gateway, 同步新增的路由定义
        this.publisher.publishEvent(new RefreshRoutesEvent(this));

        return true;
    }

}
